package com.cctc.mychat.server.handler.Message;

import com.cctc.mychat.common.protocol.message.impl.request.ChatRequestMessage;
import com.cctc.mychat.common.protocol.message.impl.response.ChatResponseMessage;
import com.cctc.mychat.common.session.Session;
import com.cctc.mychat.common.session.SessionManager;
import com.cctc.mychat.common.util.JsonUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage request) throws Exception {
        System.out.println("[ChatRequestMessageHandler] 聊天消息：" + JsonUtils.toJson(request));

        Channel fromUserChannel = ctx.channel();
        Session fromUserSession = SessionManager.getSession(fromUserChannel);

        ChatResponseMessage response = ChatResponseMessage.builder().fromUserName(fromUserSession.getUserName()).build();

        String toUserName = request.getToUserName();
        Channel toUserChannel = SessionManager.getChannel(toUserName);
        if (toUserChannel != null && SessionManager.hasLogin(toUserChannel)) {
            response.setSuccess(true);
            response.setData(request.getData());
            toUserChannel.writeAndFlush(response).addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("[ChatRequestMessageHandler] 发送成功！！！");
                }
            });
        } else {
            response.setSuccess(false);
            String reason = "接收用户 {" + toUserName + "} 不存在（已注销）！！！";
            response.setReason(reason);
            System.err.println("[ChatRequestMessageHandler] 发送失败，原因：" + reason);
            ctx.writeAndFlush(response);
        }
    }
}
